﻿#include <QDebug>
#include <QMouseEvent>
#include <QPainter>
#include <QGraphicsItem>

#include "customview.h"


CustomView::CustomView()
    : m_pLineItem(nullptr)
    , m_bPressItem(false)
    , m_bNewEdge(false)
    , m_dScale(1)
{
    //元素锯齿
    setRenderHint(QPainter::Antialiasing);
    setMouseTracking(true);//跟踪鼠标位置
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorUnderMouse);
}

CustomView::~CustomView()
{
    //析构所有node
}

void CustomView::paintEvent(QPaintEvent *event)
{
    QPainter painter(viewport());
    painter.setPen(QColor("#D3D3D3"));
    QFont font("Arial", 40);
    painter.setFont(font);

    painter.drawText(rect().x(), rect().y(), rect().width(), rect().height() - 40, Qt::AlignCenter, "GraphVisual");
    QString strText = QStringLiteral("微信公众号：高二的笔记");
    font.setBold(true);
    font.setPixelSize(20);
    painter.setFont(font);
    painter.drawText(rect().x(), rect().y(), rect().width(), rect().height() + 50, Qt::AlignCenter, strText);
    QGraphicsView::paintEvent(event);
}

void CustomView::wheelEvent(QWheelEvent *pEvent)
{
    //链接：https://www.cnblogs.com/ybqjymy/p/13745284.html?ivk_sa=1024320u
    if (pEvent->modifiers() == Qt::CTRL) {

        if((pEvent->delta() > 0) && (m_dScale >= 50)) {
            //最大放大到原始图像的50倍
            return;
        }
        else if((pEvent->delta() < 0) && (m_dScale <= 0.01)) {
            //图像缩小到自适应大小之后就不继续缩小
            return;//重置图片大小和位置，使之自适应控件窗口大小
        }
        else {
            m_dScale = this->matrix().m11();

            // 获取鼠标滚轮的距离
            int wheelDeltaValue = pEvent->delta();
            // 向上滚动，放大
            if (wheelDeltaValue > 0)
            {
                this->scale(1.2, 1.2);
            }
            // 向下滚动，缩小
            else
            {
                this->scale(1.0 / 1.2, 1.0 / 1.2);
            }
            update();
        }

    }
}

void CustomView::mouseMoveEvent(QMouseEvent *event)
{
    return QGraphicsView::mouseMoveEvent(event);
}

void CustomView::mousePressEvent(QMouseEvent *event)
{
    return QGraphicsView::mousePressEvent(event);
}

void CustomView::mouseReleaseEvent(QMouseEvent *event)
{
    return QGraphicsView::mouseReleaseEvent(event);
}

QPoint CustomView::toScenePoint(const QPoint &point)
{
    QPointF pointF = mapToScene(point);
    return pointF.toPoint();
}
